﻿using LCL.LogNet;
using LCL.Network;
using LCL.Network.Enthernet;
using LCL.Threading;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace LCL.SoftUpdateServer
{
    public partial class FrmSoftUpdateServer : Form
    {
        public FrmSoftUpdateServer()
        {
            InitializeComponent();
        }
        private SystemVersion version = new SystemVersion("1.0.1");
        private ILogNet lognet;
        private Random random = new Random();
        private Timer timer = new Timer();
        private Dictionary<string, long> loginData = new Dictionary<string, long>();
        private SimpleHybirdLock hybirdLock = new SimpleHybirdLock();

        private void Form1_Load(object sender, EventArgs e)
        {
            // 加载版本号
            if (File.Exists("version.txt"))
            {
                textBox1.Text = Encoding.Default.GetString(File.ReadAllBytes("version.txt"));
                version = new SystemVersion(textBox1.Text);
            }

            if (!Directory.Exists(Application.StartupPath + @"\Demo"))
            {
                Directory.CreateDirectory(Application.StartupPath + @"\Demo");
            }

            lognet = new LogNetSingle("logs.txt");
            lognet.BeforeSaveToFile += LogNet_BeforeSaveToFile;

            LoadData();
            timer.Interval = 3000;
            timer.Tick += Timer_Tick;
            timer.Start();
        }

        private long countOld = 1;
        private void Timer_Tick(object sender, EventArgs e)
        {
            if (countOld == 0) return;
            countOld = 0;
            long Count = 0;

            List<dataMy> list = new List<dataMy>();
            hybirdLock.Enter();

            foreach (var m in loginData)
            {
                list.Add(new dataMy(m.Key, m.Value));
            }

            hybirdLock.Leave();

            list.Sort();
            list.Reverse();

            while (dataGridView1.RowCount < list.Count)
            {
                dataGridView1.Rows.Add();
            }

            while (dataGridView1.RowCount > list.Count)
            {
                dataGridView1.Rows.RemoveAt(0);
            }

            // 赋值
            for (int i = 0; i < list.Count; i++)
            {
                dataGridView1.Rows[i].Cells[0].Value = list[i].Key;
                dataGridView1.Rows[i].Cells[1].Value = list[i].Value.ToString();
                Count += list[i].Value;
            }

            label2.Text = "总计：" + Count.ToString();

            // 统计省份功能
            List<dataMy> shengfen = new List<dataMy>();
            for (int i = 0; i < list.Count; i++)
            {
                string tmp = string.Empty;
                if (list[i].Key.IndexOf('省') > 0)
                {
                    tmp = list[i].Key.Substring(0, list[i].Key.IndexOf('省') + 1);
                }
                else if (list[i].Key.Contains("北京市"))
                {
                    tmp = "北京市";
                }
                else if (list[i].Key.Contains("上海市"))
                {
                    tmp = "上海市";
                }
                else if (list[i].Key.Contains("天津市"))
                {
                    tmp = "天津市";
                }
                else if (list[i].Key.Contains("重庆市"))
                {
                    tmp = "重庆市";
                }
                else if (list[i].Key.IndexOf('区') > 0)
                {
                    tmp = list[i].Key.Substring(0, list[i].Key.IndexOf('区') + 1);
                }

                if (string.IsNullOrEmpty(tmp)) continue;

                dataMy dataMy = shengfen.Find(m => m.Key == tmp);
                if (dataMy == null)
                {
                    shengfen.Add(new dataMy(tmp, list[i].Value));
                }
                else
                {
                    dataMy.Value += list[i].Value;
                }
            }

            shengfen.Sort();
            shengfen.Reverse();
            while (dataGridView2.RowCount < shengfen.Count)
            {
                dataGridView2.Rows.Add();
            }

            while (dataGridView2.RowCount > shengfen.Count)
            {
                dataGridView2.Rows.RemoveAt(0);
            }

            // 赋值
            for (int i = 0; i < shengfen.Count; i++)
            {
                dataGridView2.Rows[i].Cells[0].Value = shengfen[i].Key;
                dataGridView2.Rows[i].Cells[1].Value = shengfen[i].Value.ToString();
            }

        }

        private void LogNet_BeforeSaveToFile(object sender,LogEventArgs e)
        {
            Invoke(new Action(() =>
            {
                if (e.HslMessage.Degree !=LogLevel.FATAL)
                {
                    textBox2.AppendText(e.HslMessage.ToString() + Environment.NewLine);
                }
            }));
        }

        private void LoadData()
        {
            hybirdLock.Enter();
            loginData.Clear();
            if (File.Exists("City.txt"))
            {
                StreamReader sr = new StreamReader("City.txt", Encoding.Default);
                while (true)
                {
                    string city = sr.ReadLine();
                    if (city == null) break;

                    string count = sr.ReadLine();
                    if(string.IsNullOrWhiteSpace(count))count="0";
                    loginData.Add(city, long.Parse(count));
                }
                sr.Close();
            }
            hybirdLock.Leave();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            version = new SystemVersion(textBox1.Text);
            File.WriteAllBytes("version.txt", Encoding.Default.GetBytes(textBox1.Text));

            MessageBox.Show("更新成功");
        }
        //测试
        private void button2_Click(object sender, EventArgs e)
        {
            MessageBox.Show(GetAddressByIp("47.92.5.140"));
        }

        private string GetAddressByIp(string ip)
        {
            try
            {
                WebClient webClient = new WebClient();

                webClient.Encoding = Encoding.UTF8;
                webClient.Headers.Add("Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
                webClient.Headers.Add("Accept-Language", "zh-cn");//ja-jp
                webClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71");
                webClient.Headers.Add("Content-Type", "text/html");
                webClient.Headers.Add("Content-Type", "image/jpeg");
                //webClient.Headers.Add("Connection", "Keep-Alive");
                webClient.Headers.Add("Accept-Encoding", "gzip,deflate");

                byte[] data = webClient.DownloadData("http://www.ip138.com/ips138.asp?ip=" + ip + "&action=2");
                webClient.Dispose();

                string result = Encoding.Default.GetString(data);

                Match match = Regex.Match(result, "<ul class=\"ul1\"><li>[^<]+");
                if (match == null)
                {
                    return string.Empty;
                }

                return match.Value.Substring(25);
            }
            catch
            {
                return string.Empty;
            }
        }
        private NetSimplifyServer simplifyServer;
        private void Form1_Shown(object sender, EventArgs e)
        {
            NetStart();
            NetStart2();
            Timer_Tick(null, new EventArgs());
        }
        private void NetStart()
        {
            simplifyServer = new NetSimplifyServer();
            simplifyServer.ReceiveStringEvent += SimplifyServer_ReceiveStringEvent;
            simplifyServer.ServerStart(18467);
        }
       
        private void SimplifyServer_ReceiveStringEvent(AppSession arg1, NetHandle handle, string msg )
        {
            if(handle == 1)
            {
                simplifyServer.SendMessage( arg1, handle, version.ToString( ) );
                string address = GetAddressByIp( arg1.IpAddress );
                lognet.Info( arg1.IpAddress.PadRight( 15 )+" ["+msg.PadRight( 8 )+"] ["+address+"]" );
                AddDict( address );
            }
            else if(handle == 2)
            {
                simplifyServer.SendMessage( arg1, random.Next( 10000 ), "这是一条测试的数据：" + random.Next( 10000 ).ToString( ) );
            }
            else
            {
                simplifyServer.SendMessage( arg1, handle, msg );
            }
        }

        private void AddDict(string address)
        {
            if (string.IsNullOrEmpty(address)) return;

            if (address.IndexOf(' ') > 0)
            {
                address = address.Substring(0, address.IndexOf(' '));
            }

            hybirdLock.Enter();
            if (loginData.ContainsKey(address))
            {
                loginData[address]++;
            }
            else
            {
                loginData.Add(address, 1);
            }
            hybirdLock.Leave();

            countOld++;
        }
        NetSoftUpdateServer softUpdateServer;
        private void NetStart2()
        {
            softUpdateServer = new NetSoftUpdateServer();
            softUpdateServer.FileUpdatePath = Application.StartupPath + @"\Demo";
            softUpdateServer.ServerStart(18468);
        }

        private void FrmSoftUpdateServer_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)//当用户点击窗体右上角X按钮或(Alt + F4)时 发生      
            {
                e.Cancel = true;
                this.ShowInTaskbar = false;
                this.myIcon.Icon = this.Icon;
                this.Hide();
            }    
        }

        private void myIcon_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                myMenu.Show();
            }
            if (e.Button == MouseButtons.Left)
            {
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
            }       
        }
        private void myIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            //判断是否已经最小化于托盘 
            if (WindowState == FormWindowState.Minimized)
            {
                //还原窗体显示 
                WindowState = FormWindowState.Normal;
                //激活窗体并给予它焦点 
                this.Activate();
                //任务栏区显示图标 
                this.ShowInTaskbar = true;
                //托盘区图标隐藏 
                myIcon.Visible = false;
            }
        }
        private void 退出程序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();//关闭当前对象(即窗体) 
            Application.Exit();//通过Application类的静态方法Exit()退出应用程序 
        }

        private void 显示窗口ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.Visible == false) this.Visible = true;//假如当前窗口没显示则显示当前窗口 
        }

        private void 隐藏窗口ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.Visible == true) this.Visible = false;//假如当前窗口为显示的则隐藏窗口 
        }

        private void FrmSoftUpdateServer_SizeChanged(object sender, EventArgs e)
        {
            //判断是否选择的是最小化按钮 
            if (WindowState == FormWindowState.Minimized)
            {
                //隐藏任务栏区图标 
                this.ShowInTaskbar = false;
                //图标显示在托盘区 
                myIcon.Visible = true;
            }
        }

       
    }
    public class dataMy : IComparable<dataMy>
    {
        public dataMy()
        {

        }
        public dataMy(string key, long value)
        {
            Key = key;
            Value = value;
        }
        public string Key { get; set; }
        public long Value { get; set; }

        public int CompareTo(dataMy other)
        {
            return Value.CompareTo(other.Value);
        }
    }
}
